package com.ansion.commonchat.contact.sync;

import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;

import com.ansion.basedb.dao.bean.SyncAdapterColumns;
import com.ansion.commonchat.contact.bean.ContactsIds;
import com.ansion.commonchat.contact.systemcontact.AndroidContactsFactory;
import com.ansion.exception.ExceptionExtension;
import com.ansion.log.VLog;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.permission.RealRxPermission;

/**
 * Class for managing contacts sync related mOperations
 */
@SuppressLint("NewApi")
public class ContactManager {

    private static final String TAG = "ContactManager";

    /**
     * Add account for sync contacts
     *
     * @param context     context
     * @param accountName account name
     */
    public static void createAccount(Context context, String accountName) {

        if (null == context || TextUtils.isEmpty(accountName)) {
            return;
        }

        if (AndroidContactsFactory.hasAllowReadContacts()) {
            if (!isExistAccount(context, accountName)) {

                Account cocoAccount = new Account(accountName,
                        SyncAdapterColumns.ACCOUNT_TYPE);
                AccountManager.get(context).addAccountExplicitly(cocoAccount,
                        null, null);

                ContentResolver.setSyncAutomatically(cocoAccount,
                        "com.android.contacts", true);
                ContentResolver.setMasterSyncAutomatically(true);
            }

            deleteOtherAccount(context, accountName);
        }
    }

    public static void deleteALLAccount(Context context) {
        if (null == context) {
            return;
        }

        AccountManager accountManager = AccountManager.get(context);

        Account[] accounts = accountManager
                .getAccountsByType(SyncAdapterColumns.ACCOUNT_TYPE);

        if (null != accounts && accounts.length > 0) {
            for (Account account : accounts) {
                if ((null != account) && !TextUtils.isEmpty(account.name)) {
                    AccountManager.get(context).removeAccount(
                            new Account(account.name,
                                    SyncAdapterColumns.ACCOUNT_TYPE), null,
                            null);
                }
            }
        }
    }

    /**
     * check whether exist account by account name and type
     *
     * @param context     context
     * @param accountName account name
     * @return whether exist account
     */
    public static boolean isExistAccount(Context context, String accountName) {

        boolean isExist = false;

        if (null == context || TextUtils.isEmpty(accountName)) {
            return isExist;
        }

        AccountManager accountManager = AccountManager.get(context);

        Account[] accounts = accountManager
                .getAccountsByType(SyncAdapterColumns.ACCOUNT_TYPE);

        if (null != accounts && accounts.length > 0) {
            for (Account account : accounts) {
                if ((null != account) && (accountName.equals(account.name))) {
                    isExist = true;
                    break;
                }
            }
        }

        return isExist;
    }










    public static long getCocoUserIdByUri(Context context, Uri uri) {

        long uid = ContactUtil.INVALID_ID;

        if (null == context || null == uri) {
            return uid;
        }

        //fix online crash
        if (!RealRxPermission.getInstance().isGranted(Manifest.permission.READ_CONTACTS)) {
            return uid;
        }
        Cursor c = null;
        try {
            c = context.getContentResolver().query(uri,
                    new String[]{Data.DATA5, RawContacts.SOURCE_ID}, null, null, null);
            if (c.moveToNext()) {
                uid = c.getLong(c.getColumnIndex(Data.DATA5));
                if (uid == 0) {
                    uid = c.getLong(c.getColumnIndex(RawContacts.SOURCE_ID));
                }
            }
        } catch (Exception e) {
            ExceptionExtension.throwThrowable(e);
        } finally {
            if (c != null) {
                c.close();
            }
        }

        return uid;
    }

    @SuppressLint("Range")
    public static String getCocoTypeByUri(Context context, Uri uri) {
        String type = "";
        if (null == context || null == uri) {
            return type;
        }

        Cursor c = context.getContentResolver().query(uri,
                new String[]{Data.MIMETYPE}, null, null, null);

        try {
            if (c.moveToNext()) {
                type = c.getString(c.getColumnIndex(Data.MIMETYPE));
            }
        } catch (Exception e) {
            VLog.e(TAG, e);
        } finally {
            if (c != null) {
                c.close();
            }
        }

        return type;
    }



    public static ContactsIds lookupLocalContact(ContentResolver resolver,
                                                 String accountName, String phoneNumber) {
        ContactsIds contactIds = new ContactsIds();

        final Cursor c = resolver.query(Data.CONTENT_URI,
                new String[]{Data.CONTACT_ID, Data.RAW_CONTACT_ID},
                "NOT (account_type NOT NULL AND account_type =? ) AND NOT (account_name NOT NULL AND account_name =? ) AND "
                        + Phone.NUMBER + "=?", new String[]{SyncAdapterColumns.ACCOUNT_TYPE, accountName,
                        phoneNumber}, null);

        try {
            if (c.moveToFirst()) {
                contactIds.mContactsId = c.getLong(c
                        .getColumnIndex(Data.CONTACT_ID));
                contactIds.mRawContactsId = c.getLong(c
                        .getColumnIndex(Data.RAW_CONTACT_ID));
            }
        } catch (Exception e) {
            VLog.e(TAG, e);
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return contactIds;
    }


    private static void deleteOtherAccount(Context context, String accountName) {
        if (null == context || TextUtils.isEmpty(accountName)) {
            return;
        }

        AccountManager accountManager = AccountManager.get(context);

        Account[] accounts = accountManager
                .getAccountsByType(SyncAdapterColumns.ACCOUNT_TYPE);

        if (null != accounts && accounts.length > 0) {
            for (Account account : accounts) {
                if ((null != account) && !TextUtils.isEmpty(account.name)
                        && (!accountName.equals(account.name))) {
                    AccountManager.get(context).removeAccount(
                            new Account(account.name,
                                    SyncAdapterColumns.ACCOUNT_TYPE), null,
                            null);
                }
            }
        }
    }
}
